<template>
    <div ref="chartRef" style="width: 100%; height: 600px"></div>
  </template>
  
  <script setup>
  import { onMounted, onUnmounted, ref } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { 
    queryHealthRecord,
    updateHealthRecord,
    deleteHealthRecord,
    addHealthRecord
  } from '@/api/record';

  import * as echarts from 'echarts';
  import axios from 'axios';
  
  const chartRef = ref(null);
  let myChart = null;
  
  const dateList = ref([]);
  const stepsData = ref([]);
  const sleepData = ref([]);
  const waterData = ref([]);
  
  const processData = (records) => {
    // 按日期排序
    const sortedRecords = [...records].sort(
      (a, b) => new Date(a.recordDate) - new Date(b.recordDate)
    );
    
    // 处理数据
    dateList.value = sortedRecords.map(item => item.recordDate.split('T')[0]);
    stepsData.value = sortedRecords.map(item => item.steps);
    sleepData.value = sortedRecords.map(item => item.sleepDuration);
    waterData.value = sortedRecords.map(item => item.waterIntake);
  };
  
  const initChart = () => {
    if (!chartRef.value) return;
    
    myChart = echarts.init(chartRef.value);
    
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          let tooltip = params[0].axisValue + '<br>';
          params.forEach(item => {
            let unit = '';
            if (item.seriesName === '睡眠时长') unit = ' 小时';
            else if (item.seriesName === '饮水量') unit = ' ml';
            else unit = ' 步';
            tooltip += `${item.marker} ${item.seriesName}: ${item.value}${unit}<br>`;
          });
          return tooltip;
        }
      },
      legend: {
        data: ['步数', '睡眠时长', '饮水量'],
        top: 30
      },
      grid: {
        top: 80,
        bottom: 30
      },
      xAxis: {
        type: 'category',
        data: dateList.value,
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '步数/饮水量',
          position: 'left',
        },
        {
          type: 'value',
          name: '睡眠时长 (小时)',
          position: 'right',
          axisLabel: {
            formatter: '{value} h'
          }
        }
      ],
      series: [
        {
          name: '步数',
          type: 'line',
          data: stepsData.value,
          yAxisIndex: 0,
          smooth: true,
          itemStyle: {
            color: '#5470C6'
          }
        },
        {
          name: '睡眠时长',
          type: 'line',
          data: sleepData.value,
          yAxisIndex: 1,
          smooth: true,
          itemStyle: {
            color: '#91CC75'
          }
        },
        {
          name: '饮水量',
          type: 'line',
          data: waterData.value,
          yAxisIndex: 0,
          smooth: true,
          itemStyle: {
            color: '#EE6666'
          }
        }
      ]
    };
  
    myChart.setOption(option);
    window.addEventListener('resize', () => myChart.resize());
  };
  
  const fetchData = async () => {
  try {
    const userId = parseInt(localStorage.getItem('aimid'));
    if (isNaN(userId)) {
      console.error('无效的用户ID');
      return;
    }

    const params = {
      userId,
      startDate: "2000-01-01",
      endDate: "3000-01-01",
      pageIndex: 1,
      pageSize: 5
    };

    console.log('请求参数:', params);
    const response = await queryHealthRecord(params);
    console.log('接口响应:', response);

    // 调整响应结构判断
    if (response?.code === "000") {
      // 处理嵌套数据结构
      const records = response.data?.records || [];
      
      if (records.length === 0) {
        console.warn('获取到空数据集');
        return;
      }
      
      processData(records);
      initChart();
    } else {
      // 显示完整的错误信息
      const errorMsg = response?.msg || '未知错误';
      console.error(`请求失败: ${errorMsg}`, response);
    }
  } catch (error) {
    // 增强错误处理
    if (error.name === 'AxiosError') {
      console.error('网络请求错误:', {
        code: error.code,
        message: error.message,
        config: error.config
      });
    } else {
      console.error('运行时错误:', error);
    }
  }
};

  
  onMounted(async () => {
    await fetchData();
  });
  
  onUnmounted(() => {
    if (myChart) {
      window.removeEventListener('resize', myChart.resize);
      myChart.dispose();
      myChart = null;
    }
  });
  </script>